<?php
function js() {
    if (!isset($GLOBALS['sf_loaded_jses'])) {
        $GLOBALS['sf_loaded_jses']=array();
    }
    $args=func_get_args();
    foreach ($args as $name) {
        if (in_array($name,$GLOBALS['sf_loaded_jses'])) {
            continue;
        }
        $GLOBALS['sf_loaded_jses'][]=$name;
        echo '<script type="text/javascript" src="',cg('www_root'),'statics/js/',$name,'?1"></script>';
    }
}
function css() {
    if (!isset($GLOBALS['sf_loaded_csses'])) {
        $GLOBALS['sf_loaded_csses']=array();
    }
    $args=func_get_args();
    foreach ($args as $name) {
        if (in_array($name,$GLOBALS['sf_loaded_csses'])) {
            continue;
        }
        $GLOBALS['sf_loaded_csses'][]=$name;
        echo '<link href="',cg('www_root'),'statics/css/',$name,'?2" rel="stylesheet" type="text/css" />';
    }
}
function redirect($location, $code=null) {
    if (!empty($code)) {
        header('Location: '.$location,true,$code);
    } else {
        header('Location: '.$location);
    }
    die;
}
function cs($key, $value) {
    if (!isset($GLOBALS['_SF_CONFIGS'])) {
        $GLOBALS['_SF_CONFIGS']=array();
    }
    $GLOBALS['_SF_CONFIGS'][$key]=$value;
}
function cg($key) {
    if (isset($GLOBALS['_SF_CONFIGS'][$key])) {
        return $GLOBALS['_SF_CONFIGS'][$key];
    }
    return false;
}
function url($argv) {
    $www_root=cg('www_root');
    $url_parts=parse_url($www_root);
    $www_root=$url_parts['path'];
    
    if (is_scalar($argv)) {
        return $www_root.$argv;
    } if (is_array($argv)) {
        if (isset($GLOBALS['_SF_URL_RULES'])) {
            $rules=$GLOBALS['_SF_URL_RULES'];
        } else {
            $rules=array();
            $raw_rules=cg('url_rules');
            $rules=url_rule_compile($raw_rules);  
            $GLOBALS['_SF_URL_RULES']=$rules;
        }
        foreach ($rules as $rule) {
            $have_all=false;
            foreach ($rule[1] as $get_key) {
                if (!isset($argv[$get_key])) {
                    $have_all=false;
                    break;
                } else {
                    $have_all=true;
                }
            }
            if ($have_all) {
                $match_arr=$replace_arr=array();
                foreach ($rule[1] as $get_key) {
                    $match_arr[]='$'.$get_key;
                    $replace_arr[]=$argv[$get_key];
                    unset($argv[$get_key]);
                }
                
                $url=$www_root.ltrim(str_replace($match_arr,
                                        $replace_arr,
                                        $rule[2]),'/');
                break;
            }
        }
        if (empty($url)) {
            $url=$www_root;
        }
        if (count($argv)>0) {
            $query_string='';
            foreach ($argv as $k=>$v) {
                $query_string=urlencode($k).'='.urlencode($v);
            }
            $url.='?'.$query_string;
        }
        return $url;
    } else {
        return $www_root;
    }
}
function url_parse() {
    if (isset($GLOBALS['_SF_URL_RULES'])) {
        $rules=$GLOBALS['_SF_URL_RULES'];
    } else {
        $rules=array();
        $raw_rules=cg('url_rules');
        if (!$raw_rules) {
            return;
        }
        $rules=url_rule_compile($raw_rules);  
        $GLOBALS['_SF_URL_RULES']=$rules;
    }
    $url_parts=parse_url(cg('www_root'));
    $uri=substr($_SERVER['REQUEST_URI'],strlen($url_parts['path'])-1);
    foreach ($rules as $rule) {
        if (preg_match($rule[0] ,$uri, $m)) {
            foreach ($rule[1] as $get_key) {
                $_GET[$get_key] = next($m);
            }
            break;
        }
    }
}
function url_rule_compile($raw_rules) {
    $rules=array();
    static $uri_component_pattern='([^\/\.]+)';
    foreach (@$raw_rules as $raw_rule) {
        preg_match_all('/\$'.$uri_component_pattern.'/',$raw_rule,$m);
        $required_argv=array();
        $replace_arr=array();
        foreach ($m[1] as $v) {
            $required_argv[]=$v;
            $match_arr[]='$'.$v;
        }

        $place_holder=time();
        $replace_arr=array_fill(0, count($match_arr), $place_holder);
        $rule=preg_quote(
                str_replace($match_arr,$place_holder,$raw_rule),
                '/'
                );
        $rule='/'.str_replace($place_holder,$uri_component_pattern,$rule).'/';
        $rules[]=array($rule,$required_argv,$raw_rule);
    }
    return $rules;
}
function get_root_url($url) {
    $url_parts=parse_url($url);
    $root_url=$url_parts['scheme'].'://'.$url_parts['host'];
    if (!empty($url_parts['port'])) {
        $root_url.=':'.$url_parts['port'];
    }
    return $root_url;
}

function htmlize($input) {
    //$input=htmlspecialchars($input);
    $input=trim($input);
    $input=str_replace('<','&lt;',$input);
    $input=str_replace('>','&gt;',$input);
    $input=preg_replace('#(https?://[a-zA-Z\d&=\./%\-~@();,?_+]+)#i','<a href="$1" target="_blank">$1</a>',$input);
    $input=preg_replace("/[\n \r\t]{3,}/","\n\n",$input);
    $input=str_replace("\n",'<br />',$input);
    return $input;
}


/*
例子
$rs=getIncrementalPoints(array(0,23),array(10=>50,12=>20,16=>40,20=>60,4=>10));
print_r($rs);
*/
function getIncrementalPoints($range, $sample_points, $debug=false) {
    $results_points=array();
    ksort($sample_points);
    $sample_points_indexes=array_keys($sample_points);
    $min_sample_index=current($sample_points_indexes);
    $i=$min_sample_index;
    /*
        循环分两阶段：
        1）从min_sample_index到range[1]
        2）从range[0]到min_sample_index
    */
    while (true) {
        if (isset($sample_points[$i])) {
            $current_value=$sample_points[$i];
            $next_index=next($sample_points_indexes);
            if ($next_index===false) {
                reset($sample_points_indexes);
                $next_index=current($sample_points_indexes);
            }
            $next_value=$sample_points[$next_index];
            if ($next_index<$i) {
                $increment=($next_value-$current_value)/(($range[1]-$i)+$next_index);
            } else {
                $increment=($next_value-$current_value)/($next_index-$i+1);
            }
            if ($debug) {
                echo "from $i to $next_index increment:$increment\n";
            }
        }
        $results_points[$i]=$current_value;
        $current_value=$current_value+$increment;
        ++$i;
        if ($i>$range[1]) {
            $i=$range[0];//进入第二个阶段
        }
        
        if ($i==$min_sample_index) {
            //只有从0开始，才有可能等于min_sample_index，所以这里意味着是第二个阶段了
            break;
        }
    }
    ksort($results_points);
    return $results_points;
}

function increaseWithDay($start_num, $start_day, $increment_rate) {
    $start_d=strtotime($start_day)/86400;
    $current_d=time()/86400;
    return $start_num*(pow(1+$increment_rate,$current_d-$start_d));
}
function urlize($url) {
    $url=str_replace(array('À','Á','Â','Ã','Ä','Å'),'A',$url);
    $url=str_replace('Ç','C',$url);
    $url=str_replace(array('È','É','Ê','Ë'),'E',$url);
    $url=str_replace(array('Ì','Í','Î','Ï'),'I',$url);
    $url=str_replace('Ð','D',$url);
    $url=str_replace('Ñ','N',$url);
    $url=str_replace(array('Ò','Ó','Ô','Õ','Ö'),'O',$url);
    $url=str_replace('×','x',$url);
    //$url=str_replace('Ø','',$url);
    $url=str_replace(array('Ù','Ú','Û','Ü'),'U',$url);
    $url=str_replace(array('Ý','ý','ÿ'),'y',$url);
    //$url=str_replace('Þ','',$url);
    //$url=str_replace('ß','',$url);
    $url=str_replace(array('à','á','â','ã','ä','å'),'a',$url);
    //$url=str_replace('æ','',$url);
    $url=str_replace('ç','c',$url);
    $url=str_replace(array('è','é','ê','ë'),'e',$url);
    $url=str_replace(array('ì','í','î','ï'),'i',$url);
    //$url=str_replace('ð','',$url);
    $url=str_replace('ñ','n',$url);
    $url=str_replace(array('ò','ó','ô','õ','ö'),'o',$url);
    //$url=str_replace('÷','',$url);
    //$url=str_replace('ø','',$url);
    $url=str_replace(array('ù','ú','û','ü'),'u',$url);
    //$url=str_replace('þ','',$url);
	//$url=ereg_replace("\/","-",$url);
    $url=preg_replace('/[^a-zA-Z0-9_\-]/','-',$url);
    $url=strtolower($url);
    $url=trim($url,'-');
    if (empty($url)) {
        $url='-';
    }
	$url=urlencode($url);
	return $url;
}

function _t_set_locale($lc) {
    putenv('LC_ALL='.$lc);
    setlocale(LC_ALL, $lc);
}
function _t($string) {
    if (!isset($GLOBALS['sf_text'])) {
        $lc=getenv('LC_ALL');
        $locale_file=SF_ROOT_DIR.'/text/'.$lc.'.txt';
        if (file_exists($locale_file)) {
            $GLOBALS['sf_text']=parse_ini_file($locale_file);
        }
    }
    if (isset($GLOBALS['sf_text'][$string])) {
        return $GLOBALS['sf_text'][$string];
    }
    return $string;
}
/*
    type {
       p(abnu)//pcdata
       a//attr
       j//js value
    }
    
*/
function _e($str, $flags='pab', $return=false) {
    $str=htmlspecialchars(trim($str));
    if (strlen($flags)>1) {
        if ($flags[0]=='p') {
            $l=strlen($flags);
            $handled_commands=array();
            for ($i=1;$i<$l;++$i) {
                if (in_array($flags[$i], $handled_commands)) {
                    continue;
                }
                if ($flags[$i]=='a') {
                    $str=preg_replace('#(https?://[a-zA-Z\d&=\./%\-~@();,?_+]+)#i','<a href="$1" target="_blank">$1</a>',$str);
                    $handled_commands[]=$flags[$i];
                } else if ($flags[$i]=='n') {
                    $str=preg_replace("/[\n \r\t]{3,}/","\n\n",$str);
                    $handled_commands[]=$flags[$i];
                } else if ($flags[$i]=='b') {
                    $str=str_replace("\n",'<br />',$str);
                    $handled_commands[]=$flags[$i];
                }
            }
        }
    }
    if ($return) {
        return $str;
    }
    echo $str;
}

/*
当访客未登录为用户的时候，如果用到session，则需要force_start。
因为这个函数会再start之前先检测sid cookie是否存在

一些需要force的场景：
1) 登录(比较特殊的一个例子，因为这个动作结束之后用户就可能变为登录用户了)
2) SfNotice
3) 验证码
*/
function sf_session_start($force_start=false) {
    if (!isset($GLOBALS['sf_session_started'])) {
        if ($force_start || isset($_COOKIE['sid'])) {
            @session_start();
            $GLOBALS['sf_session_started']=true;
        }   
    }
}

function getCurrentUrl() {
    if (isset($_SERVER['REQUEST_URI'])) {
        return 'http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
    } else {
        return $_SERVER["SCRIPT_URI"];
    }
}
function getCurrentUrlNoHost() {
    if (isset($_SERVER['REQUEST_URI'])) {
        return $_SERVER['REQUEST_URI'];
    } else {
        return $_SERVER['SCRIPT_URI'];
    }
}
//if (!function_exists('locale_accept_from_http')) {
    function my_locale_accept_from_http($accept_language) {
        $locale='en_US';
        if (!empty($accept_language)) {
            $accept_langs=explode(',',$accept_language);
            foreach ($accept_langs as $lang) {
                if (stripos($lang,'zh-cn')!==false) {
                    $locale='zh_CN';
                    break;
                } else if (stripos($lang,'zh-tw')!==false) {
                    $locale='zh_TW';
                    break;
                } else if (stripos($lang,'zh')!==false) {
                    $locale='zh_CN';
                    break;
                } else if (stripos($lang,'ja')) {
                    $locale='ja';
                    break;
                } else if (stripos($lang,'ko')) {
                    $locale='ko';
                    break;
                } else if (stripos($lang,'es')) {
                    $locale='es';
                    break;
                }
            }
        }
        return $locale;
    }
//}

function cursor_pagination($url, $prev_cursor, $next_cursor) {
    if (empty($prev_cursor)) {
        $page_up = " <span class='page_no_link'>首页</span> <span class='page_no_link'>上一页</span>";//如果是第一页，“第一页”和“上一页”不显示
    } else {
        $page_up = " <a href='".substr($url,0,-1)."'>首页</a> <a href='".$url."prev=".$prev_cursor."'>上一页</a> ";
    }   

    if (empty($next_cursor)) {
        $page_down = " <span class='page_no_link'>下一页</span> <span class='page_no_link'>末页</span>";//如果是最后一页，“最后一页”和“下一页”不显示
    } else {
        $page_down = " <a href='".$url."next=".$next_cursor."'>下一页</a> <a href='".$url."next=end'>末页</a> ";
    }  
    $page_show = '<span class="pagination">'.$page_up.$page_down.'</span>';
    return $page_show;
}

function txt_detect_encoding($txt) {
    $enc=mb_detect_encoding($txt,array('UTF-8','GBK','UTF-16LE','UTF-16BE','UTF-16','BIG5'));
    if ($enc=='CP936') {//GB18030基本兼容GBK
        $enc='GB18030';
    }
    return $enc;
}
function txt_to_utf8($txt) {
    $enc=txt_detect_encoding($txt);
    if ($enc!='UTF-8') {
        $txt=iconv($enc,'UTF-8',$txt);
    }
    return $txt;
}
function txt_utf8_len($txt) {
    return mb_strlen($txt,'UTF-8');
}
function txt_utf8_substr($txt,$start,$len) {
    return mb_substr($txt,$start,$len,'UTF-8');
}
function insertwbr($str,$seg_len=8) {
    $len=txt_utf8_len($str);
    if ($len<=$seg_len) {
        return $str;
    }
    $wbr_str='';
    for ($start=0;$start<$len;$start+=$seg_len) {
        $wbr_str.=txt_utf8_substr($str,$start,$seg_len).'<wbr />';
    }
    return $wbr_str;
}
function set_lang($lang) {
    cs('lang', $lang);
    putenv('LC_ALL='.$lang);
    setlocale(LC_ALL,$lang);
}
function get_tz_by_ip($ip) {
    $info=@geoip_record_by_name($ip);
    if (empty($info['country_code'])) {
        return false;
    }
    return geoip_time_zone_by_country_and_region($info['country_code'],$info['region']);
}

if ( !function_exists('sys_get_temp_dir')) {
    function sys_get_temp_dir() {
        if( $temp=getenv('TMP') )        return $temp;
        if( $temp=getenv('TEMP') )        return $temp;
        if( $temp=getenv('TMPDIR') )    return $temp;
        $temp=tempnam(__FILE__,'');
        if (file_exists($temp)) {
            unlink($temp);
            return dirname($temp);
        }
        return '/tmp';
    }
}

if ( !function_exists('_') ) {
    function _($str) {
        return $str;
    }
    function gettext($str) {
        return $str;
    }
    function bind_textdomain_codeset($domain, $codeset) {
    }
    function bindtextdomain($domain, $directory) {
    }
    function dcgettext($domain, $message, $category) {
        return $message;
    }
    function dcngettext ($domain, $msgid1, $msgid2, $n, $category) {
        return $msgid1;
    }
    function dgettext($domain, $message) {
        return $message;
    }
    function dngettext($domain, $msgid1, $msgid2, $n) {
        return $msgid1;
    }
    function textdomain($text_domain) {
        return $text_domain;
    }
}
